#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"

BACKEND_PORT=${BACKEND_PORT:-8000}
FRONTEND_PORT=${FRONTEND_PORT:-15173}
API_HOST=${API_HOST:-104.129.59.158}

kill_port() {
  local port="$1"
  local pids
  pids=$(lsof -ti tcp:"$port" 2>/dev/null || true)
  if [ -n "${pids:-}" ]; then
    echo "[warn] 端口 $port 被占用，准备结束进程: $pids"
    kill $pids 2>/dev/null || true
    sleep 1
    local still
    still=$(lsof -ti tcp:"$port" 2>/dev/null || true)
    if [ -n "${still:-}" ]; then
      echo "[warn] 进程未退出，强制 kill -9: $still"
      kill -9 $still 2>/dev/null || true
      sleep 0.5
    fi
  fi
}

kill_node_processes() {
  echo "[info] 清理所有相关的 Node.js 进程"
  # 杀死所有包含 pnpm preview 的进程
  pkill -f "pnpm preview" 2>/dev/null || true
  # 杀死所有包含 vite preview 的进程
  pkill -f "vite preview" 2>/dev/null || true
  sleep 1
}

echo "[info] 清理端口和进程"
kill_node_processes
# 清理可能的端口冲突
for port in 4173 4174 4175 4176 4177 4178 ${BACKEND_PORT} ${FRONTEND_PORT}; do
  kill_port "$port"
done

echo "[info] 启动后端（uvicorn, prod）"
(
  cd "$ROOT_DIR/server"
  if [ -f requirements.txt ]; then
    PY_CMD="python3"
    if command -v python3.12 >/dev/null 2>&1; then
      PY_CMD="python3.12"
    fi
    DESIRED_VER=$($PY_CMD -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")')
    if [ -d .venv ]; then
      if [ -x .venv/bin/python ]; then
        CURRENT_VER=$(./.venv/bin/python -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")' || echo "")
      else
        CURRENT_VER=""
      fi
      if [ "$CURRENT_VER" != "$DESIRED_VER" ]; then
        echo "[info] 现有虚拟环境 Python 版本为 $CURRENT_VER，与期望 $DESIRED_VER 不一致，重建 .venv"
        rm -rf .venv
      fi
    fi
    if [ ! -d .venv ]; then
      "$PY_CMD" -m venv .venv
    fi
    # shellcheck disable=SC1091
    source .venv/bin/activate
    pip install -U pip
    pip install -r requirements.txt
  fi
  export $(grep -v '^#' "$ROOT_DIR/.env" 2>/dev/null || true | xargs -0 2>/dev/null || true)
  export REDIS_URL=${REDIS_URL:-redis://localhost:6379}
  export DATABASE_URL=${DATABASE_URL:-postgresql+psycopg://ignite_user:ignite_password@localhost:5432/textlabel_db}
  nohup python -m uvicorn app.main:app --host 0.0.0.0 --port ${BACKEND_PORT} >/tmp/textlabel-backend.log 2>&1 &
  echo $! > /tmp/textlabel-backend.pid
)

echo "[info] 构建并预览前端（Vite, prod）"
(
  cd "$ROOT_DIR/web"
  if command -v pnpm &>/dev/null; then
    pnpm install
    VITE_API_BASE="http://${API_HOST}:${BACKEND_PORT}/api" pnpm build
    # 确保前端启动在指定端口
    nohup pnpm preview -- --host 0.0.0.0 --port ${FRONTEND_PORT} --strictPort >/tmp/textlabel-frontend.log 2>&1 & echo $! > /tmp/textlabel-frontend.pid
  elif command -v npm &>/dev/null; then
    npm install
    VITE_API_BASE="http://${API_HOST}:${BACKEND_PORT}/api" npm run build
    # 确保前端启动在指定端口
    nohup npm run preview -- --host 0.0.0.0 --port ${FRONTEND_PORT} --strictPort >/tmp/textlabel-frontend.log 2>&1 & echo $! > /tmp/textlabel-frontend.pid
  else
    echo "[error] 未找到 pnpm/npm，请安装 Node.js 包管理器后再试"
    exit 1
  fi
)

# 检测前端实际运行的端口
ACTUAL_FRONTEND_PORT=${FRONTEND_PORT}
if [ -f /tmp/textlabel-frontend.log ]; then
  # 从日志中提取实际端口
  ACTUAL_PORT=$(grep -o "Network: http://.*:\([0-9]*\)/" /tmp/textlabel-frontend.log | head -1 | grep -o "[0-9]*" | tail -1)
  if [ -n "$ACTUAL_PORT" ]; then
    ACTUAL_FRONTEND_PORT=$ACTUAL_PORT
  fi
fi

echo "[done] 前端 http://0.0.0.0:${ACTUAL_FRONTEND_PORT}  API http://${API_HOST}:${BACKEND_PORT}/api"
